package com.study.portal.controller.action;

import com.opensymphony.xwork2.ActionContext;
import com.study.portal.pojo.UserAccount;
import com.study.portal.service.IUserAccountService;
import com.study.portal.util.ConstantUtil;
import com.study.portal.util.StringUtils;
import com.study.portal.util.StrutsUtil;
import com.study.portal.util.bean.LoginUesrBean;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 1177448482378255074L;

	private String url;// 登录成功后跳转连接
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	private IUserAccountService userAccountService;

	public void setUserAccountService(IUserAccountService userAccountService) {
		this.userAccountService = userAccountService;
	}

	private String userEmail;
	private String userPwd;

	public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

    public String getUserPwd() {
		return userPwd;
	}

	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}

	/**
	 * 用户登录
	 * 
	 * @return
	 */
	public String login() {
		if(StrutsUtil.isGetMethod()){
			return "login";
		}
		if(StringUtils.isEmpty(userEmail)){
			messageInfoBean.addMsg("请输入登录名称！");
		}
		if(StringUtils.isEmpty(userPwd)){
			messageInfoBean.addMsg("请输入登录密码！");
		}
		if(messageInfoBean.getMsgs().size()>0){
			messageInfoBean.setRedirect(StrutsUtil.getRequestUrl());//跳转的连接
			return MSG;
		}
		
		UserAccount user = this.userAccountService.login(userEmail, userPwd);
		if (user != null) {
			LoginUesrBean loginUesrBean = new LoginUesrBean();
			loginUesrBean.setUserAccount(user);
			ActionContext.getContext().getSession()
					.put(ConstantUtil.LOGIN_USER_BEAN, loginUesrBean);
			this.messageInfoBean.addMsg("登录成功！");
			if(!StringUtils.isEmpty(url)){
				this.messageInfoBean.setRedirect(url);//跳转的连接
			}else{
				url = StrutsUtil.getActionUrl("home","user");
				this.messageInfoBean.setRedirect(url);//跳转的连接
			}
			return MSG;
		} else {
			this.messageInfoBean.addMsg("用户名或密码错误！请重新登录");
			url = StrutsUtil.getActionUrl("login");
			this.messageInfoBean.setRedirect(url);//跳转的连接
			remove();
			return MSG;
		}
		//return "index";
	}
	
	/**
	 * 用户登出
	 * 
	 * @return
	 */
	public String logout() {
		remove();
		return "index";
	}

	private void remove() {
		ActionContext.getContext().getSession()
				.remove(ConstantUtil.LOGIN_USER_BEAN);
	}

}
